"""
Logging utilities
"""
import os
import logging
import datetime
from pathlib import Path

class Logger:
    """Class for logging mesh optimization operations"""
    
    def __init__(self, log_dir=None, log_level=logging.INFO):
        """
        Initialize the logger
        
        Parameters:
        -----------
        log_dir : str, optional
            Directory to store log files
        log_level : int
            Logging level
        """
        # Set default log directory if not provided
        if log_dir is None:
            log_dir = os.path.join(
                Path(__file__).parent.parent.parent,
                'logs'
            )
        
        # Create log directory if it doesn't exist
        os.makedirs(log_dir, exist_ok=True)
        
        # Create timestamp for log file
        timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
        log_file = os.path.join(log_dir, f"mesh_optimizer_{timestamp}.log")
        
        # Configure logger
        self.logger = logging.getLogger("MeshOptimizer")
        self.logger.setLevel(log_level)
        
        # Create file handler
        file_handler = logging.FileHandler(log_file)
        file_handler.setLevel(log_level)
        
        # Create console handler
        console_handler = logging.StreamHandler()
        console_handler.setLevel(log_level)
        
        # Create formatter
        formatter = logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
        )
        file_handler.setFormatter(formatter)
        console_handler.setFormatter(formatter)
        
        # Add handlers to logger
        self.logger.addHandler(file_handler)
        self.logger.addHandler(console_handler)
        
        self.log_file = log_file
        self.logger.info(f"Logger initialized. Log file: {log_file}")
    
    def info(self, message):
        """Log info message"""
        self.logger.info(message)
    
    def warning(self, message):
        """Log warning message"""
        self.logger.warning(message)
    
    def error(self, message):
        """Log error message"""
        self.logger.error(message)
    
    def debug(self, message):
        """Log debug message"""
        self.logger.debug(message)
    
    def log_mesh_stats(self, mesh_data, prefix=""):
        """
        Log mesh statistics
        
        Parameters:
        -----------
        mesh_data : dict
            Dictionary containing mesh data
        prefix : str
            Prefix for log messages
        """
        if 'points' in mesh_data and 'cells' in mesh_data:
            num_points = len(mesh_data['points'])
            num_cells = len(mesh_data['cells'])
            
            self.info(f"{prefix}Mesh statistics:")
            self.info(f"{prefix}  - Number of points: {num_points}")
            self.info(f"{prefix}  - Number of cells: {num_cells}")
    
    def log_quality_metrics(self, quality_metrics, prefix=""):
        """
        Log quality metrics
        
        Parameters:
        -----------
        quality_metrics : dict
            Dictionary containing quality metrics
        prefix : str
            Prefix for log messages
        """
        self.info(f"{prefix}Quality metrics:")
        self.info(f"{prefix}  - Minimum quality: {quality_metrics['min_quality']:.4f}")
        self.info(f"{prefix}  - Maximum quality: {quality_metrics['max_quality']:.4f}")
        self.info(f"{prefix}  - Average quality: {quality_metrics['avg_quality']:.4f}")
        self.info(f"{prefix}  - Standard deviation: {quality_metrics['std_quality']:.4f}")
    
    def log_optimization_results(self, optimization_results, prefix=""):
        """
        Log optimization results
        
        Parameters:
        -----------
        optimization_results : dict
            Dictionary containing optimization results
        prefix : str
            Prefix for log messages
        """
        improvement = optimization_results['improvement']
        
        self.info(f"{prefix}Optimization results:")
        self.info(f"{prefix}  - Original average quality: {improvement['original_avg_quality']:.4f}")
        self.info(f"{prefix}  - Optimized average quality: {improvement['optimized_avg_quality']:.4f}")
        self.info(f"{prefix}  - Improvement percentage: {improvement['improvement_percentage']:.2f}%")
    
    def get_log_file(self):
        """Get the path to the log file"""
        return self.log_file 